package com.mate.cloud.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mate.cloud.auth.constant.UserExceptionCodeEnum;
import com.mate.cloud.auth.entity.UmsUser;
import com.mate.cloud.auth.exception.UserBizException;
import com.mate.cloud.auth.mapper.UserMapper;
import com.mate.cloud.auth.param.UserRegister;
import com.mate.cloud.auth.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
/**
 * @description:    java类作用描述
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/2/3 16:58
 * @updateUser:     MI
 * @updateTime:     2025/2/3 16:58
 * @updateRemark:   修改内容
 * @version:        v1.0
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UmsUser> implements UserService {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    public UmsUser selectByUsername(String userName) {
        LambdaQueryWrapper<UmsUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(UmsUser::getUserName,userName);
        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    public boolean register(UserRegister userRegister) {
        // 检查用户名是否已存在
        if (baseMapper.selectCount(new LambdaQueryWrapper<UmsUser>()
                .eq(UmsUser::getUserName, userRegister.getUserName())) > 0) {
            throw new UserBizException(UserExceptionCodeEnum.USER_NAME_EXISTS_WARN.getCode());
        }

        // 校验密码是否一致
        if (StrUtil.isNotBlank(userRegister.getConfirmPassWord()) && !StrUtil.equals(userRegister.getPassWord(), userRegister.getConfirmPassWord())) {
            throw new UserBizException(UserExceptionCodeEnum.CONFIRM_PASSWORD_ERROR.getCode());
        }
        UmsUser user = new UmsUser();
        BeanUtils.copyProperties(userRegister, user);
        user.setUserName(userRegister.getUserName());
        user.setPassWord(ENCODER.encode(userRegister.getPassWord()));

        return save(user);
    }
}
